package util;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class ObjectUtil {
    public static <T extends Comparable<T>> int compare(T o1, T o2) {
        return o1.compareTo(o2);
    }

    /**
     * 启动n个线程同时执行n个任务 等待所有任务执行完毕后返回所有结果
     *
     * @param runnables 每个结果下标对应传入时下标
     * @return
     */
    @SuppressWarnings("rawtypes")
    @SafeVarargs
    public static List<Object> executes(Callable<Object>... callable) {
        Objects.requireNonNull(callable);
        ExecutorService threadPool = Executors
                .newFixedThreadPool(callable.length);
        List<Future> futures = new ArrayList<>();
        for (Callable<Object> r : callable) {
            futures.add(threadPool.submit(r));
        }
        threadPool.shutdown();
        while (true) {
            if (threadPool.isTerminated()) {
                break;
            }
        }
        return futures.stream().map(f -> {
            try {
                return f.get();
            } catch (Exception e) {
                return null;
            }
        }).collect(Collectors.toList());
    }
}